package day12;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import org.junit.Test;

public class JDBCDemo {

	@Test
	public void testSelectAll() {
		try {
//		    1、加载驱动Class.forName("");  
			Class.forName("com.mysql.jdbc.Driver");
//			2、获得连接对象Connection
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java2012?useUnicode=true&characterEncoding=UTF-8", "root", "1234");
//			3、写sql语句
			String sql = "SELECT `id`,`name`,`age`,`gender` FROM `student`";
//			4、创建Statement(一艘船)
			Statement statement = connection.createStatement();
//			5、执行sql语句
//			     (1) 更新类（更改了表里面数据）：delete/update/insert     executeUpdate()
//			           返回值：int，表示你影响的行数
//			      (2)查询（没有改变表里面数据）:  select                              executeQuery()
//			           返回值：结果集ResultSet
			ResultSet resultSet = statement.executeQuery(sql);
			ArrayList<Student> list = new ArrayList<Student>();
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String name = resultSet.getString("name");
				int age = resultSet.getInt("age");
				String gender = resultSet.getString("gender");
				
				// 没一次变量，就可以拿到数据库表中的一行数据，这一行数据就代表一个学生的信息
				Student student = new Student(id, name, age, gender);
				list.add(student);
			}
			
			for (Student student : list) {
				System.out.println(student);
			}
			
//			6、关闭连接
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}
}
